package com.lujianfei.powersearch.ui.createOrUpdate

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.os.Looper
import android.os.Message
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.base.BaseActivity
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.databinding.ActivityCreateOrUpdateBinding
import com.lujianfei.powersearch.ui.createOrUpdate.viewmodel.CreateOrUpdateViewModel
import com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit.adapter.ImageViewEditAdapter
import com.lujianfei.powersearch.ui.dialog.BottomDialog
import com.lujianfei.powersearch.ui.preview.FullScreenPreviewActivity
import com.lujianfei.powersearch.ui.sort.touchhelper.SortDragTouchCallback
import com.lujianfei.powersearch.utils.Constant
import com.lujianfei.powersearch.utils.DensityUtils
import com.lujianfei.powersearch.utils.ImageUtils
import com.lujianfei.powersearch.utils.SystemUtils
import com.lujianfei.powersearch.utils.ToastUtils
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


class CreateOrUpdateActivity : BaseActivity<ActivityCreateOrUpdateBinding>() {

    companion object {
        private const val CAMERA_CODE = 1001
        private const val ALBUM_CODE = 1000
        private const val APP_SELECT_CODE = 1002
        const val PARAM_KEY_ID = "id"

        fun jumpCreateOrUpdateActivity(context: Context,item: SearchItemModel?, requestCode: Int = -1) {
            val intent = Intent(context, CreateOrUpdateActivity::class.java)
            intent.putExtra("data", item)
            if (requestCode != -1) {
                if (context is Activity) {
                    context.startActivityForResult(intent, requestCode)
                }
            } else {
                context.startActivity(intent)
            }
        }

        fun jumpCreateActivity(context: Context,item: SearchItemModel?) {
            val intent = Intent(context, CreateOrUpdateActivity::class.java)
            intent.putExtra("parentId", item!!.id)
            intent.putExtra("parentName", item.name)
            context.startActivity(intent)
        }
    }

    private val mCreateOrUpdateViewModel:CreateOrUpdateViewModel by lazy { buildViewModel() }

    private var mImageUriFromCamera: Uri? = null

    private val imageViewEditAdapter by lazy { ImageViewEditAdapter() }

    override fun resourceId() = R.layout.activity_create_or_update

    override fun initView() {
        binding?.vm = mCreateOrUpdateViewModel
        val mLinearLayoutManager = LinearLayoutManager(this)
        mLinearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL

        val sortDragTouchCallback = SortDragTouchCallback(imageViewEditAdapter, verticalMove = false)
        val itemTouchHelper = ItemTouchHelper(sortDragTouchCallback)
        itemTouchHelper.attachToRecyclerView(binding?.photoList)
        binding?.photoList?.apply {
            layoutManager = mLinearLayoutManager
            adapter = imageViewEditAdapter
            addItemDecoration(object : ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    outRect.left = DensityUtils.dip2px(5f)
                }
            })
        }
    }

    override fun initData() {
        parseIntent()
        if (null == mCreateOrUpdateViewModel.searchItemModel) {
            if (TextUtils.isEmpty(mCreateOrUpdateViewModel.parentName)) {
                setTitleMiddleText("新增子节点")
            } else {
                setTitleMiddleText("新增" + mCreateOrUpdateViewModel.parentName + "的子节点")
            }
            mCreateOrUpdateViewModel.showDeleteButton.set(false)
        } else {
            setTitleMiddleText("修改节点:" + mCreateOrUpdateViewModel.searchItemModel?.name)
            mCreateOrUpdateViewModel.updateDataToView()
            mCreateOrUpdateViewModel.showDeleteButton.set(true)

        }
        imageViewEditAdapter.setData(mCreateOrUpdateViewModel.getImageList())

    }

    override fun initEvent() {
        binding?.btDelete?.setOnClickListener { deleteAndFinish() }
        binding?.btBindApp?.setOnClickListener {
            AppSelectActivity.startAppSelect(this@CreateOrUpdateActivity, requestCode = APP_SELECT_CODE)
        }
        binding?.btBindAppDelete?.setOnClickListener {
            mCreateOrUpdateViewModel.packageName.set("")
            mCreateOrUpdateViewModel.bindAppName.set("")
        }

        // 开始时间
        binding?.editStartDate?.onTimeReceive = { timeStr, timeStamp ->
            mCreateOrUpdateViewModel.startDateStr.set(timeStr)
            mCreateOrUpdateViewModel.startDateTimeStamp = timeStamp
        }
        binding?.editStartTime?.shouldBlock = {
            val result = mCreateOrUpdateViewModel.startDateStr.get()?.isBlank() == true
            if (result) {
                ToastUtils.show("先设置开始日期")
            }
            result
        }
        binding?.editStartTime?.onTimeReceive = { timeStr, timeStamp ->
            mCreateOrUpdateViewModel.startTimeStr.set(timeStr)
            mCreateOrUpdateViewModel.startTimeTimeStamp = timeStamp
        }


        // 结束时间
        binding?.editEndDate?.onTimeReceive = { timeStr, timeStamp ->
            mCreateOrUpdateViewModel.endDateStr.set(timeStr)
            mCreateOrUpdateViewModel.endDateTimeStamp = timeStamp
        }
        binding?.editEndTime?.shouldBlock = {
            val result = mCreateOrUpdateViewModel.endDateStr.get()?.isBlank() == true
            if (result) {
                ToastUtils.show("先设置结束日期")
            }
            result
        }
        binding?.editEndTime?.onTimeReceive = { timeStr, timeStamp ->
            mCreateOrUpdateViewModel.endTimeStr.set(timeStr)
            mCreateOrUpdateViewModel.endTimeTimeStamp = timeStamp
        }
        mCreateOrUpdateViewModel.finishCallback = {
            finish()
        }

        imageViewEditAdapter.onAddClickListener = {
            showBottomDialog()
        }
        imageViewEditAdapter.onPhotoClickListener = {
            val imageListString = imageViewEditAdapter.getFinalImagePath()
            val currentIndex = imageListString.split(",").indexOf(it.imageUri?.toString())
            FullScreenPreviewActivity.startPreview(this@CreateOrUpdateActivity, images = imageListString, currentIndex = currentIndex)
        }
        imageViewEditAdapter.onRemoveClickListener = {
            if (it.hasUrl()) {
                mCreateOrUpdateViewModel.removeImagePath(it.imageUrl)
            }
        }
    }

    private fun openCamera() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val file = createFile()
        mImageUriFromCamera = FileProvider.getUriForFile(this, "com.lujianfei.powersearch.fileProvider", file)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUriFromCamera)
        startActivityForResult(intent, CAMERA_CODE)
    }

    private fun openAlbum() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*|video/*"
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        startActivityForResult(intent, ALBUM_CODE)
    }

    private fun createFile():File {
        val sdcardDir = Environment.getExternalStorageDirectory()
        val myPhotoDir = File(sdcardDir, "power_search")
        if (!myPhotoDir.exists()) {
            myPhotoDir.mkdir()
        }
        val file = File(myPhotoDir, "${System.currentTimeMillis()}.jpg")
        if (!file.exists()) file.createNewFile()

        val pathArray = arrayOf(file.absolutePath)
        val typeArray = arrayOf("image/jpeg")
        MediaScannerConnection.scanFile(SystemUtils.getApplicationContext(), pathArray, typeArray) { s, uri -> Log.d("ImageUtils", "onScanCompleted  s->$s") }
        return file
    }

    private fun showBottomDialog() {
        val mBottomDialog = BottomDialog()
        mBottomDialog.addItem(BottomDialog.ItemData(label = "拍照") {
            openCamera()
            it.dismiss()
        })
        mBottomDialog.addItem(BottomDialog.ItemData(label = "相册") {
            openAlbum()
            it.dismiss()
        })
        mBottomDialog.addItem(BottomDialog.ItemData(label = "取消") {
            it.dismiss()
        })
        mBottomDialog.showNow(supportFragmentManager, "mBottomDialog")
    }

    private fun deleteAndFinish() {
        if (null != mCreateOrUpdateViewModel.searchItemModel) {
            AlertDialog.Builder(this@CreateOrUpdateActivity).setTitle("提示")
                    .setMessage("确定要删除 \"" + mCreateOrUpdateViewModel.searchItemModel?.name + "\" ?")
                    .setPositiveButton("确定") { dialog, which ->
                        dialog.dismiss()
                        mCreateOrUpdateViewModel.deleteCurrentAndSubItem(mCreateOrUpdateViewModel.searchItemModel)
                    }.setNegativeButton("取消", null).show()
        }
    }


    private fun parseIntent() {
        val intent = intent
        mCreateOrUpdateViewModel.searchItemModel = intent.getParcelableExtra("data")
        mCreateOrUpdateViewModel.parentId = intent.getLongExtra("parentId", Constant.RootId.toLong())
        mCreateOrUpdateViewModel.parentName = intent.getStringExtra("parentName")
    }

    private fun saveAndFinish() {
        if (TextUtils.isEmpty(mCreateOrUpdateViewModel.info.get())) {
            ToastUtils.show("请输入名称")
            return
        }
        if (null == mCreateOrUpdateViewModel.searchItemModel) {
            mCreateOrUpdateViewModel.searchItemModel = SearchItemModel()
            mCreateOrUpdateViewModel.searchItemModel?.createTime = System.currentTimeMillis()
            mCreateOrUpdateViewModel.searchItemModel?.parentId = mCreateOrUpdateViewModel.parentId
        }
        mCreateOrUpdateViewModel.searchItemModel?.name = mCreateOrUpdateViewModel.info.get()
        mCreateOrUpdateViewModel.searchItemModel?.keywords = mCreateOrUpdateViewModel.keyword.get()
        mCreateOrUpdateViewModel.searchItemModel?.location = mCreateOrUpdateViewModel.location.get()
        mCreateOrUpdateViewModel.searchItemModel?.cost = mCreateOrUpdateViewModel.cost.get()
        mCreateOrUpdateViewModel.searchItemModel?.packageName = mCreateOrUpdateViewModel.packageName.get()
        mCreateOrUpdateViewModel.searchItemModel?.appName = mCreateOrUpdateViewModel.bindAppName.get()
        mCreateOrUpdateViewModel.searchItemModel?.startTime = mCreateOrUpdateViewModel.startTimeStamp
        mCreateOrUpdateViewModel.searchItemModel?.endTime = mCreateOrUpdateViewModel.endTimeStamp
        mCreateOrUpdateViewModel.searchItemModel?.imagePath = imageViewEditAdapter.getFinalImagePath()
        mCreateOrUpdateViewModel.searchItemModel?.updateTime = System.currentTimeMillis()
        if (mCreateOrUpdateViewModel.searchItemModel?.createTime == 0L) {
            mCreateOrUpdateViewModel.searchItemModel?.createTime = mCreateOrUpdateViewModel.searchItemModel?.updateTime?:0L
        }
        mCreateOrUpdateViewModel.searchItemModel?.save()
        val intent = Intent()
        intent.putExtra(PARAM_KEY_ID, mCreateOrUpdateViewModel.searchItemModel?.id?:-1L)
        setResult(RESULT_OK, intent)
        finish()
    }

    private val executorService: ExecutorService = Executors.newSingleThreadExecutor()

    private val mHandler = android.os.Handler(Looper.getMainLooper(), this::handleMessage)

    override val titleBarResId: Int = R.id.toolbar

    override val menuResId: Int = R.menu.create_edit_menu

    override fun handleRightButton(itemId: Int) {
        super.handleRightButton(itemId)
        when (itemId) {
            R.id.action_save -> saveAndFinish()
        }
    }

    private fun handleMessage(msg: Message): Boolean {
        if (msg.what == ALBUM_CODE) {
            val imagePath = msg.obj as String
            imageViewEditAdapter.addData(imagePath)
            return true
        }
        return false
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            CAMERA_CODE -> {
                imageViewEditAdapter.addData(mImageUriFromCamera)
            }
            ALBUM_CODE -> {
                val clipData = data?.clipData
                val albumUriList = arrayListOf<Uri>()
                if (clipData != null) {
                    for (i in 0 until clipData.itemCount) {
                        clipData.getItemAt(i).uri?.let {
                            albumUriList.add(it)
                        }
                    }
                } else {
                    data?.data?.let {
                        albumUriList.add(it)
                    }
                }

                for (uri in albumUriList) {
                    executorService.submit {
                        val compressResult = ImageUtils.copyUriToInternalStorage(this, uri)
                        mHandler.sendMessage(mHandler.obtainMessage(ALBUM_CODE,compressResult))
                    }
                }
            }
            APP_SELECT_CODE-> {
                loadBindApp(data)
            }
        }
    }

    private fun loadBindApp(data: Intent?) {
        val packageName = data?.getStringExtra("packageName")
        val name = data?.getStringExtra("name")
        val parseContent = mCreateOrUpdateViewModel.bindLink.get()?:""
        if (parseContent.contains("amap") && name?.contains("高德地图") == true) {
            mCreateOrUpdateViewModel.packageName.set(parseContent)
        } else if (parseContent.contains("dianping") && name?.contains("大众点评") == true) {
            mCreateOrUpdateViewModel.packageName.set(parseContent)
        } else {
            mCreateOrUpdateViewModel.packageName.set(packageName?:"")
        }
        mCreateOrUpdateViewModel.bindAppName.set(name?:"")
    }
}